<template>
  <div class="smart-home">
    <!-- 标题区域：刷新按钮 + 主标题 + 区域选择器（单选弹窗） -->
    <div class="title-container">
      <!-- 手动刷新按钮 -->
      <button
          class="refresh-btn"
          @click="handleRefresh"
          :disabled="isRefreshing || !systemOnline"
      >
        {{ isRefreshing ? '刷新中...' : '🔄 刷新' }}
      </button>
      <h1>🏠 智慧家居环境监控</h1>
      <!-- 核心：区域选择器（修复点击事件和弹窗逻辑） -->
      <div class="area-selector">
        <!-- 1. 去掉@click.stop，避免阻止按钮点击事件；去掉!areaOptions.length禁用条件 -->
        <button
            class="current-area-btn"
            :disabled="!systemOnline"
            @click="toggleAreaPopup"
        >
          当前区域：{{ currentArea.label || '请选择区域' }}
          <span class="arrow" :class="{ rotate: isAreaPopupShow }">▼</span>
        </button>
        <!-- 2. 弹窗显示条件简化：只保留isAreaPopupShow和systemOnline（areaOptions有数据才会显示） -->
        <div
            class="area-popup"
            v-if="isAreaPopupShow && systemOnline"
        >
          <!-- 循环渲染卧室、厨房 -->
          <div
              class="area-option"
              v-for="area in areaOptions"
              :key="area.value"
              @click="selectArea(area)"
              :class="{ active: area.value === currentArea.value }"
          >
            {{ area.label }}
          </div>
        </div>
      </div>
    </div>
    <p>选择下方功能模块进行详细操作</p>

    <!-- 系统状态 -->
    <div class="system-status">
      <div class="status-item">
        <span class="status-dot" :class="systemOnline ? 'online' : 'offline'"></span>
        <span>系统状态: {{ systemOnline ? '在线' : '离线' }}</span>
      </div>
      <div class="status-item">
        <span>最后更新: {{ lastUpdateTime || '未更新' }}</span>
      </div>
      <div class="status-item">
        <span>当前用户ID: {{ targetUserId }}</span>
      </div>
      <div class="status-item">
        <span>可用区域: {{ areaOptions.map(area => area.label).join('、') }}</span> <!-- 显示已拿到的设备 -->
      </div>
    </div>

    <!-- 核心功能按钮区域 -->
    <div class="function-buttons">
      <router-link
          to="/dashboard/smart-home/HomePotted"
          class="function-btn"
          :class="{ disabled: !systemOnline }"
      >
        <div class="btn-icon">🌱</div>
        <div class="btn-text">智能盆栽</div>
      </router-link>
      <router-link
          to="/dashboard/smart-home/HomeAir"
          class="function-btn"
          :class="{ disabled: !systemOnline }"
      >
        <div class="btn-icon">💨</div>
        <div class="btn-text">智能换气</div>
      </router-link>
      <router-link
          to="/dashboard/smart-home/HomeAlert"
          class="function-btn"
          :class="{ disabled: !systemOnline }"
      >
        <div class="btn-icon">🛡️</div>
        <div class="btn-text">智能安防</div>
      </router-link>
    </div>

    <!-- 子路由出口 -->
    <router-view class="sub-router-view"></router-view>

    <!-- 底部说明 -->
    <div class="bottom-note">
      <p>💡 点击对应模块进入详细监控页面 | 当前监控区域：{{ currentArea.label || '未选择' }}</p>
      <p v-if="!systemOnline" class="offline-note">⚠️ 系统离线状态下，部分功能可能受限</p>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useFarmStore } from '@/stores/farm'
import { deviceAPI } from '@/api/deviceAPI'

export default {
  name: 'SmartHome',
  setup() {
    const farmStore = useFarmStore()

    // 响应式数据
    const lastUpdateTime = ref('')
    const isSystemOnline = ref(true)
    const isRefreshing = ref(false)

    // 区域选择核心数据
    const areaOptions = ref([]) // 存储卧室、厨房
    const currentArea = ref({}) // 当前选中的区域
    const isAreaPopupShow = ref(false) // 弹窗显示状态
    const targetUserId = ref(999) // 固定查询user_id=999

    // 系统在线状态计算属性
    const systemOnline = computed(() => isSystemOnline.value)

    // 修复：切换弹窗显示/隐藏（无冗余限制）
    const toggleAreaPopup = () => {
      if (!systemOnline.value) return
      isAreaPopupShow.value = !isAreaPopupShow.value
      console.log('弹窗状态：', isAreaPopupShow.value) // 调试：查看是否触发
    }

    // 修复：选择区域（确保能更新当前区域并关闭弹窗）
    const selectArea = (area) => {
      currentArea.value = area // 更新为选中的卧室/厨房
      isAreaPopupShow.value = false // 关闭弹窗
      console.log('已切换到区域：', area.label) // 调试：查看是否切换成功
    }

    // 点击页面其他地方关闭弹窗（逻辑不变）
    onMounted(() => {
      const handleClickOutside = (e) => {
        const selector = document.querySelector('.area-selector')
        if (selector && !selector.contains(e.target)) {
          isAreaPopupShow.value = false
          console.log('点击外部，关闭弹窗')
        }
      }
      document.addEventListener('click', handleClickOutside)
      return () => document.removeEventListener('click', handleClickOutside)
    })

    // 核心：获取user_id=999 + scene=home的设备列表（逻辑不变，已能拿到数据）
    const fetchHomeDevices = async () => {
      if (!systemOnline.value) return
      try {
        console.log(`查询user_id=999 + scene=home的设备`)
        const devices = await deviceAPI.getDevicesByUserId(targetUserId.value)

        // 过滤出scene=home的设备（兼容大小写）
        const homeDevices = devices.filter(device =>
            device.scene?.toLowerCase() === 'home'
        )
        console.log('过滤后home设备：', homeDevices.map(d => d.name)) // 打印：["卧室","厨房"]

        // 格式化为选项（value=设备id，label=设备名称）
        areaOptions.value = homeDevices.map(device => ({
          value: device.id.toString(),
          label: device.name
        }))

        // 初始化：默认选中第一个设备（卧室）
        if (areaOptions.value.length > 0 && !currentArea.value.label) {
          currentArea.value = areaOptions.value[0]
          console.log('默认选中区域：', currentArea.value.label)
        }
      } catch (error) {
        console.error('获取设备列表失败:', error)
        areaOptions.value = []
        currentArea.value = {}
      }
    }

    // 初始化系统状态
    const initSystemStatus = async () => {
      try {
        await farmStore.fetchEnvironmentalData()
        isSystemOnline.value = farmStore.isSystemOnline
        lastUpdateTime.value = farmStore.lastUpdateTime || new Date().toLocaleString('zh-CN')
        if (systemOnline.value) {
          await fetchHomeDevices() // 初始化时获取设备列表
        }
      } catch (error) {
        console.error('初始化系统状态失败:', error)
        isSystemOnline.value = false
        lastUpdateTime.value = '离线状态'
      }
    }

    // 手动刷新
    const handleRefresh = async () => {
      if (isRefreshing.value) return
      isRefreshing.value = true
      try {
        await farmStore.fetchEnvironmentalData()
        isSystemOnline.value = farmStore.isSystemOnline
        lastUpdateTime.value = farmStore.lastUpdateTime || new Date().toLocaleString('zh-CN')
        if (systemOnline.value) await fetchHomeDevices()
        alert(`刷新成功！当前区域：${currentArea.label || '未选择'}`)
      } catch (error) {
        console.error('刷新失败:', error)
        alert('刷新失败，请稍后重试')
      } finally {
        isRefreshing.value = false
      }
    }

    // 监听在线状态，同步加载设备
    watch(systemOnline, (isOnline) => {
      if (isOnline) fetchHomeDevices()
      else {
        areaOptions.value = []
        currentArea.value = {}
        isAreaPopupShow.value = false
      }
    })

    // 初始化
    onMounted(() => {
      initSystemStatus()
      const statusTimer = setInterval(initSystemStatus, 300000)
      return () => clearInterval(statusTimer)
    })

    return {
      lastUpdateTime,
      systemOnline,
      isRefreshing,
      handleRefresh,
      areaOptions,
      currentArea,
      isAreaPopupShow,
      toggleAreaPopup,
      selectArea,
      targetUserId
    }
  }
}
</script>

<style scoped>
.smart-home {
  padding: 30px;
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.title-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  gap: 15px;
  flex-wrap: wrap;
  position: relative;
}

.refresh-btn {
  background-color: #4299e1;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background-color 0.3s;
}

.refresh-btn:disabled {
  background-color: #a0aec0;
  cursor: not-allowed;
  opacity: 0.8;
}

.refresh-btn:hover:not(:disabled) {
  background-color: #3182ce;
}

.title-container h1 {
  color: #2d3748;
  margin: 0;
  font-size: 26px;
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

/* 区域选择器样式（优化层级，确保弹窗不被遮挡） */
.area-selector {
  position: relative;
  z-index: 1000; /* 提高层级，避免被其他元素遮挡 */
}

.current-area-btn {
  background-color: #f0f8fb;
  border: 1px solid #4299e1; /* 加深边框，更易点击 */
  color: #2d3748;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.current-area-btn:disabled {
  background-color: #f5f5f5;
  border-color: #e2e8f0;
  color: #a0aec0;
  cursor: not-allowed;
}

.current-area-btn:hover:not(:disabled) {
  background-color: #e8f4f8;
  border-color: #3182ce;
}

.arrow {
  font-size: 12px;
  transition: transform 0.3s ease;
}

.arrow.rotate {
  transform: rotate(180deg);
}

/* 弹窗样式（优化阴影，更易识别） */
.area-popup {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  width: 180px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  z-index: 1001; /* 弹窗层级高于按钮 */
}

.area-option {
  padding: 12px 16px;
  color: #2d3748;
  font-size: 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.area-option:hover {
  background-color: #f0f8fb;
}

.area-option.active {
  background-color: #4299e1; /* 选中时背景色，明显区分 */
  color: white;
  font-weight: 500;
}

.system-status {
  display: flex;
  align-items: center;
  gap: 25px;
  margin-bottom: 25px;
  padding: 15px 20px;
  background: #f8f9fa;
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  flex-wrap: wrap;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4a5568;
  font-size: 14px;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.status-dot.online {
  background: #48bb78;
  box-shadow: 0 0 10px rgba(72, 187, 120, 0.5);
}

.status-dot.offline {
  background: #e53e3e;
  box-shadow: 0 0 10px rgba(229, 62, 62, 0.5);
}

.function-buttons {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 25px;
}

.function-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 25px 15px;
  background: linear-gradient(135deg, #48bb78, #2d5a27);
  color: white;
  border-radius: 12px;
  text-decoration: none;
  box-shadow: 0 4px 16px rgba(72, 187, 120, 0.3);
  transition: all 0.3s ease;
  border: none;
  cursor: pointer;
}

.function-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(72, 187, 120, 0.4);
  background: linear-gradient(135deg, #38a169, #224027);
}

.function-btn.disabled {
  background: linear-gradient(135deg, #a0aec0, #718096);
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 2px 8px rgba(160, 174, 192, 0.2);
  opacity: 0.8;
}

.btn-icon {
  font-size: 40px;
  margin-bottom: 12px;
}

.btn-text {
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.sub-router-view {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.bottom-note {
  text-align: center;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 10px;
}

.bottom-note p {
  margin: 5px 0;
  color: #4a5568;
  font-size: 14px;
  line-height: 1.5;
}

.offline-note {
  color: #e53e3e !important;
  font-weight: 500;
  font-size: 15px !important;
}

/* 响应式设计：适配小屏幕 */
@media (max-width: 768px) {
  .smart-home {
    padding: 20px 15px;
  }

  .title-container {
    gap: 10px;
  }

  .title-container h1 {
    font-size: 22px;
  }

  /* 小屏幕下区域选择器独占一行 */
  .area-selector {
    width: 100%;
    margin-top: 10px;
  }

  .current-area-btn {
    width: 100%;
    justify-content: center;
    padding: 7px 14px;
    font-size: 15px;
  }

  .area-popup {
    width: 100%;
  }

  .area-option {
    padding: 11px 14px;
    font-size: 14px;
  }

  .system-status {
    padding: 12px 15px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .status-item {
    font-size: 13px;
  }

  .function-buttons {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .function-btn {
    padding: 20px 12px;
  }

  .btn-icon {
    font-size: 34px;
  }

  .btn-text {
    font-size: 15px;
  }

  .refresh-btn {
    padding: 5px 10px;
    font-size: 13px;
  }

  .sub-router-view {
    padding: 15px;
    margin-top: 15px;
  }

  .bottom-note {
    padding: 15px;
    margin-top: 20px;
  }

  .bottom-note p {
    font-size: 13px;
  }
}

/* 响应式设计：适配中屏幕 */
@media (min-width: 769px) and (max-width: 1024px) {
  .smart-home {
    padding: 25px;
  }

  .title-container h1 {
    font-size: 24px;
  }

  .function-buttons {
    grid-template-columns: repeat(2, 1fr);
    gap: 18px;
  }

  .function-btn {
    padding: 22px 14px;
  }

  .btn-icon {
    font-size: 38px;
  }

  .btn-text {
    font-size: 17px;
  }
}

/* 响应式设计：适配大屏幕 */
@media (min-width: 1025px) {
  .area-selector:hover .current-area-btn {
    background-color: #e8f4f8;
    border-color: #3182ce;
  }

  .area-option:active {
    background-color: #d6eaf8;
  }
}
</style>